package com.etxxy.common.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @category 序列化反序列化工具
 * @author yiz
 *
 */
public class SerializableUtil {

	private static final Logger logger = LoggerFactory.getLogger(SerializableUtil.class);

	/**
	 * 序列化
	 * 
	 * @param object
	 * @return
	 */
	public static byte[] serialize(Object object) {
		ObjectOutputStream oos = null;
		ByteArrayOutputStream baos = null;
		try {
			// 序列化
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			byte[] bytes = baos.toByteArray();
			return bytes;
		} catch (Exception e) {
			logger.error("Exception异常e={}", e);
		} finally {
			try {
				if (null != baos) {
					baos.close();
				}
				if (null != oos) {
					oos.close();
				}
			} catch (IOException e) {
				logger.error("关闭流IOException异常e={}", e);
			}
		}
		return null;
	}

	/**
	 * 反序列化
	 * 
	 * @param bytes
	 * @return
	 */
	public static Object deserialize(byte[] bytes) {
		ByteArrayInputStream bris = null;
		BufferedInputStream bis = null;
		ObjectInputStream ois = null;
		try {
			bris = new ByteArrayInputStream(bytes);
			bis = new BufferedInputStream(bris);
			ois = new ObjectInputStream(bis);
			Object obj = ois.readObject();
			return obj;
		} catch (IOException e) {
			logger.error("IOException异常e={}", e);
		} catch (ClassNotFoundException e) {
			logger.error("ClassNotFoundException异常e={}", e);
		} finally {
			try {
				if (null != bris) {
					bris.close();
				}
				if (null != bis) {
					bis.close();
				}
				if (null != ois) {
					ois.close();
				}
			} catch (IOException e) {
				logger.error("关闭流失败Exception=e{}", e);
			}
		}
		return null;
	}
}
